package com.wallace.downloadserver.service.impl

import com.wallace.downloadserver.bean.MyInterface
import com.wallace.downloadserver.service.ApplicationService
import com.wallace.downloadserver.service.MyInterfaceService
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.annotation.Async
import org.springframework.stereotype.Service
import org.springframework.web.context.WebApplicationContext
import org.springframework.web.method.HandlerMethod
import org.springframework.web.servlet.mvc.method.RequestMappingInfo
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping

/**
 * @Description:
 * ApplicationServiceImpl
 * @author Wallace
 * @Date 2022/1/28 10:24
 */
@Service
class ApplicationServiceImpl : ApplicationService {

    private val log: Logger = LoggerFactory.getLogger(javaClass)

    @Autowired
    private lateinit var applicationContext: WebApplicationContext

    @Autowired
    private lateinit var myInterfaceService: MyInterfaceService

    @Async(value = "WallacePool")
    override fun scanInterface() {
        log.debug("start to scan all interfaces...")
//        val urls: List<String> = arrayListOf()
        // 清空数据库的my_interface表
        myInterfaceService.deleteAll()
        val mapping: RequestMappingHandlerMapping = applicationContext.getBean(RequestMappingHandlerMapping::class.java)
        //获取url与类和方法的对应信息
        val map: Map<RequestMappingInfo, HandlerMethod> = mapping.handlerMethods
        var index = 1
        map.forEach {
            //获取url的Set集合，一个方法可能对应多个url
            val patternSet = it.key.pathPatternsCondition?.patternValues
            val handlerMethodName = it.value.method.name
            log.debug("$patternSet-->$handlerMethodName")
            val myInterface = MyInterface(id = index, methodName = handlerMethodName, path = patternSet?.toList())
            myInterfaceService.insert(myInterface)
            index++
        }
    }
}